using UnityEngine;
using UnityEngine.UI;

namespace Watermelon
{
    [RequireComponent(typeof(RectTransform), typeof(CanvasGroup))]
    public class CurrencyUI : MonoBehaviour
    {
        [SerializeField] Text text;
        [SerializeField] Image icon;

        private CanvasGroup canvasGroup;
        private RectTransform rectTransform;

        public string Text { get => text.text; set => text.text = value; }
        public Sprite Icon { get => icon.sprite; set => icon.sprite = value; }

        public bool IsVisible { get => gameObject.activeSelf; }

        private TweenCase fadeTweenCase;

        private Currency currency;

        private void Awake()
        {
            rectTransform = GetComponent<RectTransform>();
            canvasGroup = GetComponent<CanvasGroup>();
        }

        public void Initialise(Currency currency)
        {
            this.currency = currency;

            icon.sprite = currency.Icon;
            text.text = currency.AmountFormatted;

            rectTransform.sizeDelta = UIHelper.GetPanelSize(text.text.Length - 1);
        }

        public void SetAmount(int amount)
        {
            text.text = CurrenciesHelper.Format(amount);

            rectTransform.sizeDelta = UIHelper.GetPanelSize(text.text.Length - 1);
        }

        public void Show()
        {
            gameObject.SetActive(true);

            if (fadeTweenCase != null && fadeTweenCase.isActive) fadeTweenCase.Kill();

            fadeTweenCase = canvasGroup.DOFade(1, 0.3f);
        }

        public void Hide()
        {
            if (fadeTweenCase != null && fadeTweenCase.isActive) fadeTweenCase.Kill();

            fadeTweenCase = canvasGroup.DOFade(0, 0.3f).OnComplete(() => {
                gameObject.SetActive(false);
            });
        }

        public void Clear()
        {
            if (fadeTweenCase != null && fadeTweenCase.isActive) fadeTweenCase.Kill();
        }
    }
}